import React, { ReactElement, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { message } from 'antd';
import { getToken } from '@/utils/modules/auth';

interface Props {
  children: ReactElement;
}

const PrivateRoute = ({ children }: Props) => {
  const router = useNavigate();

  // 对比时间戳是否超过48小时
  const isPast48Hours = (timestamp: number): boolean => {
    // 获取当前时间戳
    const currentTimeStamp = Math.floor(Date.now() / 1000);

    // 计算时间差，单位为秒
    const timeDifference = currentTimeStamp - timestamp;

    // 定义48小时的秒数
    const hours48InSeconds = 48 * 60 * 60;

    // 判断时间差是否超过48小时
    return timeDifference > hours48InSeconds;
  };

  // 监听路由
  useEffect(() => {
    try {
      const token: string | null = getToken();
      if (token) {
        const tokenObj = JSON.parse(token);
        if (tokenObj === null || isPast48Hours(tokenObj.time)) {
          message.error('token过期，请重新登录');
          router('/login');
        }
      }
    } catch (error: any) {
      message.error(error.message || '路由守卫过程发生错误');
      router('/login');
    }
  }, []);

  // 返回路由
  return children;
};

export default PrivateRoute;
